package engine.services.impl;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import engine.parsers.ParsersClassLoader;

import engine.services.IParserClassLoader;

public class FileSytemParserClassLoaderHandlerImpl extends ClassLoader implements IParserClassLoader {

	private Log log = LogFactory.getLog(ParsersClassLoader.class);
	
	@Override
	public byte[] loadClassData(String className) throws Exception {
		File f;
		f = new File(System.getProperty("user.dir") + File.separator + "parsers" + File.separator + className);
		if (log.isDebugEnabled()) {
			log.debug("Looking for parser at path: " + f.getAbsolutePath());			
		}
		if (f.exists()) {
			int size = (int) f.length();
			byte buff[] = new byte[size];
			FileInputStream fis = new FileInputStream(f);
			DataInputStream dis = new DataInputStream(fis);
			dis.readFully(buff);
			dis.close();
			return buff;			
		} else {
			if (log.isDebugEnabled()) {
				log.debug("Parser File does not exist");				
			}
			return null;
		}
	}
	
	@SuppressWarnings({ "rawtypes" })
	public Class myFindClass(String className) throws ClassNotFoundException{
		byte classByte[];
		Class result = null;
		try {
			int startIndex = Math.max(className.lastIndexOf(".") + 1 , 0);
			String parserClass = className.substring(startIndex) + ".class";
			classByte = loadClassData(parserClass);
			if (classByte == null) {
				result = super.loadClass(className);
				return result;								
			}
			result = defineClass(className, classByte, 0, classByte.length,null);
			return result;
		} catch (Throwable t) {
			log.error("Could not load "+ className, t);
			throw new ClassNotFoundException(className);
		}
	}

}
